package cn.gson.crm.controller.teaching;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.BedRoomDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.BedRoom;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.mapper.BedroomMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/bedroomDetails")
public class BedRoomDetailsController {

	@Autowired
	private BedroomMapper brm;

	@Autowired
	private BedRoomDao brd;

	@Autowired
	private StudentDao stud;

	// 查询寝室详情（学生信息）
	@RequestMapping("student/{bedroomId}")
	@ResponseBody
	public JSONObject studentList(Student stu, @PathVariable(name = "bedroomId", required = false) Long id,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		Page<Student> pageData = (Page<Student>) brm.studentList(stu, id);

		// 组装返回结果
		JSONObject obj = new JSONObject();
		obj.put("total", pageData.getTotal());
		obj.put("rows", pageData.getResult());
		return obj;

	}
	
	/**
	 * 修改寝室长
	 * @param id
	 * @param bedroomId
	 * @return
	 */
	@GetMapping("dormitory/{id}/{bedroomId}")
	@ResponseBody
	@Transactional
	public JSONObject dormitory(@PathVariable("id") Long id,@PathVariable("bedroomId") Long bedroomId) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		BedRoom bedroom;
		Student student,oldstudent;
		//当前寝室
		bedroom = brd.findOne(bedroomId);
			if(bedroom.getStudentId()!=null) {
			 oldstudent=stud.findOne(bedroom.getStudentId().getId());
			//先修改上一个寝室长
			 oldstudent.setDormitory(false);
			 stud.save(oldstudent);
			}
				student = stud.findOne(id);
				bedroom.setStudentId(student);
				student.setDormitory(true);
				stud.save(student);
				brd.save(bedroom);
				obj.put("success", true);
			
			
		return obj;
	}
	
	/**
	 * 删除寝室的学员
	 * @param ids
	 * @return
	 */
	@GetMapping("delete_student/{id}/{bedroomId}")
	@ResponseBody
	@Transactional
	public JSONObject deleteStu(@PathVariable("id") Long id,@PathVariable("bedroomId") Long bedroomId){
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		Student student;
		BedRoom bedroom;
			//删除学员寝室中间表
			brm.deleteStudent(id);
			//根据id找到学生
			student = stud.findOne(id);
			//修改学生的是否为寝室长状态
			student.setDormitory(false);
			//提交
			stud.save(student);
			bedroom = brd.findOne(bedroomId);
			
				if(bedroom.getStudentId()!=null&&id==bedroom.getStudentId().getId()) {
							bedroom.setStudentId(null);
					}
			
				bedroom.setCount(bedroom.getCount()-1);
				bedroom.setState("空余");
				brd.save(bedroom);
			obj.put("success", true);
		return obj;
	}

	/**
	 * 打开学员换寝页面
	 * @param student
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("inbedroom/{id}/{bedroomType}/{bedroomId}")
	public String inbedroom(
			Student student,
			@PathVariable(name = "id", required = false) Long id,
			@PathVariable(name = "bedroomId", required = false) Long bedroomId,
			@PathVariable(name = "bedroomType" , required = false) String bedroomType,
			Model model) {
		
		String type = bedroomType;
		
		List<BedRoom> bedroom = brm.selectNewBedroom(bedroomType,bedroomId);
		model.addAttribute("bedroomId", bedroomId);
		model.addAttribute("bedroomType", type);
		model.addAttribute("bedroom", bedroom);
		
		return "bedroomDetails/inbedroom";
	}
	
	/**
	 * 查询所有待分寝的学员
	 * @param br
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("bedroomlist/{bedroomType}/{bedroomId}")
	@ResponseBody
	public Map<String, Object> studentlist(
			@PathVariable(name = "bedroomType" , required = false) String bedroomType,
			@PathVariable(name = "bedroomId", required = false) Long bedroomId,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,
			BedRoom bedroom) {
			Map<String, Object> obj = new HashMap<String, Object>();
			// 查询数据
				PageHelper.startPage(pageNum, pageSize);
				List<BedRoom> pageData = brm.selectNewBedroom(bedroomType,bedroomId);

				PageInfo<BedRoom> info = new PageInfo<>(pageData);

				obj.put("total", info.getTotal());
				obj.put("rows", info.getList());
				return obj;
	}
	
	
	/**
	 * 换寝
	 * @param id
	 * @param ids
	 * @return
	 */
	@RequestMapping("inbedroomstu/{id}/{ids}/{bedroomId}")
	@ResponseBody
	@Transactional
	public Map<String, Object> savebedroomstu(
			@PathVariable(name = "id", required = false) Long id,
			@PathVariable(name = "bedroomId", required = false) Long bedroomId,
			@PathVariable(name = "ids", required = false) Long ids){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		
		//删除学员寝室中间表
		brm.deleteStudent(id);
		
		//根据id找到学生
		Student student = stud.findOne(id);
		
		//修改学生的是否为寝室长状态
		student.setDormitory(false);
		
		//根据id找到旧寝室
		BedRoom oldbedroom = brd.findOne(bedroomId);
		//设置寝室长为null,如果该学员是寝室长
		if(oldbedroom.getStudentId()!=null) {
			if(oldbedroom.getStudentId().getId()==id) {
				oldbedroom.setStudentId(null);
			}
		}
		//设置原来寝室的状态
		oldbedroom.setCount(oldbedroom.getCount()-1);
		oldbedroom.setState("空余");
		
		Map<String, Object> saveParams = new HashMap<>();
		saveParams.put("dormitoryId", ids);
		saveParams.put("id",id);
		
		//根据id找到新寝室
		BedRoom newbedroom = brd.findOne(ids);
			Long renshu = newbedroom.getCount()+1;
			//如果人数满了
			if(renshu==newbedroom.getBed()) {
				newbedroom.setState("住满");
			}
			newbedroom.setCount(newbedroom.getCount() + 1);	
		// 在中间表添加一条数据
		brm.saveOneStudentToDorm(saveParams);
		//提交
		brd.save(newbedroom);

		stud.save(student);
		
		brd.save(oldbedroom);
		
		obj.put("message", "换寝成功！学员"+student.getName()+"已从"+oldbedroom.getName()+"调换到"+newbedroom.getName());
		obj.put("success", true);
		
		return obj;
	}
}
